<!-- components/TopicSelector.vue -->
<template>
  <view class="topics-container">
    <scroll-view scroll-x="true" class="topics-scroll-view">
      <view
          v-for="(topic, index) in topics"
          :key="index"
          class="topic-tag"
          :class="{ selected: isSelected(topic.id) }"
          @click="selectTopic(topic.id)"
      >
        #{{ topic.name }}
      </view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      selectedTopicId: null, // 存储当前选中的主题ID
    };
  },
  props: {
    topics: {
      type: Array,
      default: () => []
    }
  },
  methods: {
    selectTopic(topicId) {
      if (this.selectedTopicId === topicId) {
        this.selectedTopicId = null; // 如果已经选中，再次点击则取消选择
      } else {
        this.selectedTopicId = topicId; // 否则选中新的主题
      }
      this.$emit('selectTopic', this.selectedTopicId); // 发送选中的主题ID
    },
    isSelected(topicId) {
      return this.selectedTopicId === topicId;
    }
  },
}
</script>

<style>
.topics-container {
  padding: 10px 0;
  background-color: #fff; /* 背景颜色为白色 */
}

.topics-scroll-view {
  display: flex;
  flex-direction: row;
  overflow-x: auto; /* 启用横向滚动 */
  white-space: nowrap; /* 防止标签换行 */
}

.topic-tag {
  height: 30px;
  background-color: #cbc9c9;
  color: #faf8f8;
  padding: 5px 10px; /* 让标签有固定的上下内边距和左右内边距 */
  margin-right: 10px;
  border-radius: 15px;
  font-size: 14px;
  display: inline-block; /* 确保标签宽度根据内容自适应 */
}

.topic-tag.selected {
  background-color: red; /* 当被选中时背景色变为红色 */
  color: #ffffff; /* 当被选中时文字颜色变为白色 */
}
</style>
